package com.xiaotou.common;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiException;
import com.sun.jimi.core.JimiWriter;
import com.sun.jimi.core.options.JPGOptions;

public class ImageHandler {
	static Log logger = LogFactory.getLog(ImageHandler.class);
	
	public static void compile(String dest, Image imgA, Image imgB, Image imgC) {
		int quality = 100;
		int imgAwidth = imgA.getWidth(null);
		int imgAheight = imgA.getHeight(null);
		
		int imgBwidth = imgB.getWidth(null);
		int imgBheight = imgB.getHeight(null);

		int imgCwidth = imgC.getWidth(null);
		int imgCheight = imgC.getHeight(null);
		
		int imgWidth = imgCwidth+(imgAwidth+imgBwidth)/2;
		int imgHeight = imgCheight+(imgAheight+imgBheight)/2;
		BufferedImage compileImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
		
		int imgLeftPointX =0;
		int imgLeftPointY = 0;
		int imgRightBottomX =imgCwidth;
		int imgRightBottomY =imgCheight;
		int destLeftPointX =imgAwidth/2;
		int destLeftPointY = imgAheight/2;
		int destRightBottomX = imgCwidth+destLeftPointX;
		int destRightBottomY = imgCheight+destLeftPointY;
		Graphics2D g2 = (Graphics2D)compileImage.getGraphics();
		g2.setBackground(new Color(217,96,0));
	    g2.clearRect(0,0,imgWidth,imgHeight);
		g2.drawImage(imgC, destLeftPointX, destLeftPointY, destRightBottomX, destRightBottomY, imgLeftPointX, imgLeftPointY, imgRightBottomX, imgRightBottomY, null); 
		g2.drawImage(imgA, 0, 0, imgAwidth, imgAheight, 0, 0, imgAwidth, imgAheight, null); 
		g2.drawImage(imgB, destRightBottomX-imgBwidth/2, destRightBottomY-imgBheight/2,  destRightBottomX+imgBwidth/2, destRightBottomY+imgBheight/2, 0, 0, imgBwidth, imgBheight, null); 
		try {
			JPGOptions options = new JPGOptions();
			options.setQuality(quality);
			JimiWriter writer = Jimi.createJimiWriter(dest);
			writer.setSource(compileImage);
			writer.putImage(dest);
		} catch (JimiException je) {
			System.out.println(je);
		}
	}
	
}
